/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.teamreinforce.web.controllers;
 
import com.teamreinforce.ejb.beans.*;
import com.teamreinforce.ejb.entities.*;
import com.teamreinforce.ejb.model.IPerformeCollaborator;
import com.teamreinforce.ejb.model.IPerformeCommunication;
import com.teamreinforce.ejb.model.IPerformeProjects;
import com.teamreinforce.utils.TeamReinforceTimeUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.JSONArray;
import org.json.JSONObject;
import sun.reflect.generics.visitor.Reifier;

/**
 *
 * @author tidiane
 */
@WebServlet(
                name = "ControllerServlet",
                loadOnStartup = 1,
                urlPatterns = {
                                "/menu",
                                "/gestiondescollaborateurs",
                                "/gestiondesprojets",
                                "/gestiondesreunions",
                                "/gererlesprojets",
                                "/tableaudebord",
                                "/creerprojets",
                                "/modifierprojet",
                                "/modifierreunion",
                                "/creerreunion",
                                "/creercollaborateur",
                                "/affectercollaborateurprojet",
                                "/gererprojets",
                                "/gererlesreunions",
                                "/gererlescollaborateurs",
                                "/creerrisques",
                                "/creeretape",
                                "/modifieretape",
                                "/creertache",
                                "/projets",
                                "/etapes",
                                "/taches",
                                "/modifiertache",
                                "/modifiercollaborateur"
                              }
           )
public class ControllerServlet extends HttpServlet {

    @EJB
    private ProjetFacade projectF;
    
    @EJB
    private EtapeFacade etapeF;
    
    @EJB
    private TacheFacade tacheF;
    
    @EJB
    private ReunionFacade reunionF;
    
    @EJB
    private RolesFacade rolesF;
    
    @EJB
    private CollaborateurFacade collaboratorF;
    
    @EJB
    private IPerformeCollaborator pCollaborator;
    
    @EJB
    private IPerformeCollaborator pCollaborateur;
    
    @EJB
    private IPerformeProjects pProjects;
    
    @EJB
    private IPerformeCommunication pCommunication;
    
    @EJB
    private IPerformeCollaborator pCollaborators;
    
    private HttpSession session;
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */ 
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ControllerServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet ControllerServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //request.setCharacterEncoding("UTF-8");
        String userPath = request.getServletPath();
        /**
         * The collaborators management
         */
        if (userPath.equals("/gestiondescollaborateurs")){
            // TODO : Implement the action
        }
        
        /**
         * The projects management
         */
        if ( userPath.equals("/gestiondesprojets")) {
            //
        }
        
        /**
         * Edit a projet
         */ 
        if ( userPath.equals("/modifierprojet")){
            try {
                String project = request.getParameter("pid");
                Projet _projet = projectF.find(Integer.parseInt(project));
                response.setContentType("text/plain;charset=UTF-8");
                PrintWriter out = response.getWriter();
            
                out.println("{\"titre\":\""+ _projet.getTitre() +"\",\"description\":\""+ _projet.getDescription() +"\",\"ddebut\":\""+ _projet.getDateDebut() +"\",\"dfin\":\""+ _projet.getDateFin() +"\"}");
                out.close();
            }catch (Exception e){
                System.out.println(" Error " + e.getMessage());
                e.printStackTrace();
            }
        }
        /**
         * Edit a collaborateur
         */   
        if ( userPath.equals("/modifiercollaborateur")){
            try {
                String col = request.getParameter("cid");
                Collaborateur _col = collaboratorF.find(Integer.parseInt(col));
                
                JSONObject obj = new JSONObject();
                obj.put("nom", _col.getNom());
                obj.put("prenom", _col.getPrenom());
                obj.put("email", _col.getEmail());
                obj.put("telephone", _col.getTelephone());
                obj.put("portable", _col.getPortable());
                obj.put("login", _col.getLogin());
                obj.put("password", _col.getPassword());
                if ( _col.getEstAdmin() == 1)
                    obj.put("admin", "ON");
                else
                    obj.put("admin", "OFF");

                response.setContentType("text/plain;charset=UTF-8");
                PrintWriter out = response.getWriter();
                out.println(obj.toString());
                out.close();
            }catch (Exception e){
                System.out.println(" Error " + e.getMessage());
            }
        }        
        
        /**
         * Edit a reunion
         */ 
        if ( userPath.equals("/modifierreunion")){
            try {
                String reunion = request.getParameter("rid");

                Reunion _reunion = reunionF.find(Integer.parseInt(reunion));
                
                JSONArray participants = new JSONArray ();
                for ( Collaborateur c : _reunion.getCollaborateurList()){
                    JSONObject item = new JSONObject();
                    item.put("id", c.getIdCollaborateur());
                    item.put("login", c.getLogin());
                    
                    participants.put(item);
                }
                
                JSONArray autres = new JSONArray();
                for ( Collaborateur c : collaboratorF.findAll()){
                    if ( !_reunion.getCollaborateurList().contains(c)){
                        JSONObject item = new JSONObject();
                        item.put("id", c.getIdCollaborateur());
                        item.put("login", c.getLogin());
                        autres.put(item);
                    }
                }
                
                JSONObject obj = new JSONObject();
                obj.put("titre", _reunion.getTitre());
                obj.put("description", _reunion.getDescription());
                obj.put("dater", _reunion.getDateReunion());
                obj.put("hdebut", _reunion.getHeureDebut());
                obj.put("hfin", _reunion.getHeureFin());
                obj.put("salle", _reunion.getSalleReunion());
                obj.put("participants", participants);
                obj.put("autres", autres);
                
                response.setContentType("text/plain;charset=UTF-8");
                PrintWriter out = response.getWriter();
                out.println(obj.toString());
                out.close();
            }catch (Exception e){
                System.out.println(" Error " + e.getMessage());
            }
        }        
         /**
         * recuperer a reunion
         */
        
        if(userPath.equals("/gererlesreunions")){
            request.getServletContext().setAttribute("reunions", reunionF.findAll());
        }
        
         /**
         * recuperer a collaborateur
         */
        
        if(userPath.equals("/gererlescollaborateurs")){
            request.getServletContext().setAttribute("collaborateurs", collaboratorF.findAll());
        }        
         
        /**
         * Edit a etape
         */ 
        if ( userPath.equals("/modifieretape")){
            try { 
                String etape = request.getParameter("eid");
                System.out.println("EId :: " + etape);
                
                Etape _etape = etapeF.find(Integer.parseInt(etape));
                response.setContentType("text/plain;charset=UTF-8");
                PrintWriter out = response.getWriter();
                
                out.println("{\"libelle\":\""+ _etape.getLibelle() +"\",\"description\":\""+ _etape.getDescription() +"\",\"ddebut\":\""+ _etape.getDateDebut() +"\",\"dfin\":\""+ _etape.getDateFin() +"\"}");
                
                out.close();
            }catch (Exception e){
                System.out.println(" Error " + e.getMessage());
                e.printStackTrace();
            }
        }
        
        /**
         * Edit a task
         */ 
        if ( userPath.equals("/modifiertache")){
            try {
                String tache = request.getParameter("tid");

                Tache _tache = tacheF.find(Integer.parseInt(tache));
                response.setContentType("text/plain;charset=UTF-8");
                
                String collaborateur = "nobody";
                if ( _tache.getCollaborateurList().size() > 0 ){
                    collaborateur = _tache.getCollaborateurList().get(0).getLogin();
                }
                
                List<String> _collaborateurs = new ArrayList<String>();
                for ( Collaborateur c : collaboratorF.findAll()){
                    _collaborateurs.add(c.getLogin());
                }
                
                JSONArray collaborateurs = new JSONArray(_collaborateurs);
                JSONObject obj = new JSONObject();
                obj.put("collaborateurs", collaborateurs);
                obj.put("collaborateur", collaborateur);
                obj.put("libelle", _tache.getLibelle());
                obj.put("description", _tache.getDescription());
                obj.put("ddebut", _tache.getDateDebut());
                obj.put("dfin", _tache.getDateFin());
                 
                PrintWriter out = response.getWriter();
                out.println(obj.toString());
                out.close();
            }catch (Exception e){
                System.out.println(" Error " + e.getMessage());
                e.printStackTrace();
            }
        }

        /**
         * Add the step to the projet
         */
        if ( userPath.equals("/creeretape")){

        }
        
        /**
         * Steps list
         */
        if ( userPath.equals("/etapes")){
            String project = request.getQueryString();
            Projet _project = projectF.find(Integer.parseInt(project));
            getServletContext().setAttribute("projet", project);
            getServletContext().setAttribute("collaborateurs", collaboratorF.findAll());
            request.setAttribute("etapes", _project.getEtapeList());
        }
          
        /**
         * The tasks management
         */   
        if ( userPath.equals("/taches")){
            String etape = request.getQueryString();
            
            // Getting the etapes
            Etape _etape = etapeF.find(Integer.parseInt(etape));
            
            // Putting the task on the context
            getServletContext().setAttribute("etape", _etape);
            request.setAttribute("collaborateurs", pCollaborator.getAllCollaborators());
            // Getting the list of the tasks
            getServletContext().setAttribute("taches", _etape.getTacheList());
        }
           
        /**
         * 
         */
        if ( userPath.equals("/creertache")) {
            request.setAttribute("collaborateurs", pCollaborator.getAllCollaborators());
            
        } 
        /**
         * The meeting management
         */
        if ( userPath.equals("/gestiondesreunions")) {

        }
         
        /**
         * If the risque
         */
        if ( userPath.equals("/creerrisques")){
            request.setAttribute("projets", pProjects.getAllProjects());
        } 
        /**
         * The dashboard of the project
         */  
        if ( userPath.equals("/tableaudebord")){
            Projet projet;
            if ( request.getParameterNames().hasMoreElements()){
                String pid = request.getParameter("projet");
                projet = projectF.find(Integer.parseInt(pid));
                getServletContext().setAttribute("_projet", projet);
            }else{
                getServletContext().setAttribute("_projet", projectF.findAll().get(0));
            }
            
            getServletContext().setAttribute("projets", projectF.findAll());
            userPath = "/dashoard-projet";
        }

        /**
         * The list of the projects
         */
        if ( userPath.equals("/gererlesprojets")){
            // Get the projects list and set the context attributes
            request.getServletContext().setAttribute("projets", pProjects.getAllProjects());
        }

        /**
         * Affectations
         */
        if ( userPath.equals("/affectercollaborateurprojet")){
            String project = request.getQueryString();
            getServletContext().setAttribute("projet", projectF.find(Integer.parseInt(project)));
            getServletContext().setAttribute("collaborateurs", pCollaborator.getAllCollaborators());
            getServletContext().setAttribute("roles", rolesF.findAll());
        }
        /**
         * The redirection to the needed page
         */
        String url = "/WEB-INF/view" + userPath + ".jsp";

        try {
            if ( ! userPath.equals("/show-tableaudebord") && ! userPath.equals("/modifierprojet") && ! userPath.equals("/modifieretape") && ! userPath.equals("/modifiertache") && ! userPath.equals("/modifierreunion") && ! userPath.equals("/modifiercollaborateur"))
                request.getRequestDispatcher(url).forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
 
    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String userPath = request.getServletPath();
        
        String url = "/WEB-INF/view";
        /**
         * The management of the login
         * and give acces to the menu
         */
        
        if (userPath.equals("/menu")){
            String username = request.getParameter("USERNAME");
            String password = request.getParameter("PASSWORD");

            try{            String action = request.getParameter("action");
                Collaborateur collabarator = pCollaborator.getCollaborator(username, password);
                session = request.getSession();
                if ( collabarator != null ){
                    session.setAttribute("login", collabarator.getLogin());
                    session.setAttribute("nom", collabarator.getNom());
                    session.setAttribute("id", collabarator.getIdCollaborateur());
                    getServletContext().setAttribute("collaborateurs", pCollaborator.getAllCollaborators());
                    
                    url = url + userPath + ".jsp";
                    request.getRequestDispatcher(url).forward(request, response);
                }
                else {
                    userPath = "/error";
                    url = url + userPath + ".jsp";
                    request.getRequestDispatcher(url).forward(request, response);
                }
            }catch (Exception e){
                userPath = "/error";
                url = url + userPath + ".jsp";
                request.getRequestDispatcher(url).forward(request, response);
            }
        }
        
                /**
         * The meeting management
         */
        if ( userPath.equals("/gestiondesreunions")) {
            String action = request.getParameter("action");
            
            /**
             * Création d'un reunion
             */
            if ( action.equals("creer-reunion")){
                
            }
        }
        
        /**
         * Managing the collaborateur
         */
         if ( userPath.equals("/gestiondescollaborateurs")) {
            String action = request.getParameter("action");
            if ( action.equals("creer-collaborateur")) {
                try{
                    String prenom = request.getParameter("prenom");
                    String nom = request.getParameter("nom");
                    String telephone = request.getParameter("telephone");
                    String portable = request.getParameter("portable");
                    String email = request.getParameter("email");
                    String login = request.getParameter("login");
                    String password = request.getParameter("password");
                    String est_admin = request.getParameter("est_admin");

                    if (est_admin != null && est_admin.equals("on"))
                        pCollaborateur.createCollaborateur(prenom, nom, telephone, portable, email, login, password, true);
                    else
                        pCollaborateur.createCollaborateur(prenom, nom, telephone, portable, email, login, password, true);
                    request.setAttribute("message", "Collaborateur ajouté avec succès !");
                    request.setAttribute("code", "Confirmation");
                    doGet(request, response);
                    
                    }catch (Exception e){
                        request.setAttribute("message", e.getMessage());
                        request.setAttribute("code", "error");
                    System.err.println(" Error cach :: " + e.getMessage());
                    response.getWriter().println("<h1> Error : " + e.getMessage() + "</h1>");
                    response.getWriter().close();
                    }
            }
        }
        
         /**
          * Gerer les collaborateur
          */
         if ( userPath.equals("/gererlescollaborateurs")) {
             String action = request.getParameter("action");
             
             if ( action.equals("modifiercollaborateur")) {
                 try {
                    String col = request.getParameter("cid");
                    Collaborateur _col = collaboratorF.find(Integer.parseInt(col));

                    String prenom = request.getParameter("prenomcollaborateur");
                    String nom = request.getParameter("nomcollaborateur");
                    String telephone = request.getParameter("telephone");
                    String portable = request.getParameter("portable");
                    String email = request.getParameter("email");
                    String login = request.getParameter("login");
                    String password = request.getParameter("motdepasse");
                    String est_admin = request.getParameter("est_admin");

                    _col.setPrenom(prenom);
                    _col.setNom(nom);
                    _col.setTelephone(telephone);
                    _col.setPortable(portable);
                    _col.setEmail(email);
                    _col.setLogin(login);
                    _col.setPassword(password);
                    
                    if ( est_admin != null && est_admin.equals("on")) 
                        _col.setEstAdmin(1);
                    else
                        _col.setEstAdmin(0);
                    
                    collaboratorF.edit(_col);
                    
                    doGet(request, response);
                 }catch (Exception e){
                     e.printStackTrace();
                     response.getWriter().println("<h1> Error : " + e.getMessage() + "</h1>");
                     response.getWriter().close();
                 }
             }
         }
         /**
        * Managing the projets
        */ 
        if ( userPath.equals("/gererlesprojets")){
            String action = request.getParameter("action");
            System.out.println(" Action :: " + action);
            
            // Création du projet
            if ( action.equals("ceerprojet")){
                String title = request.getParameter("titre");
                String description = request.getParameter("description");
                String dateDebut = request.getParameter("ddebut");
                String dateFin = request.getParameter("dfin");
                System.out.println("Title : " + title);
                System.out.println("Description : " + description);
                try {
                    pProjects.createProject(title, description, dateDebut, dateFin);
                    request.setAttribute("code", "success");
                    request.setAttribute("message", "Projet crée avec succès !");
                    doGet(request, response);
                }catch (Exception e){
                    request.setAttribute("code", "error");
                    request.setAttribute("message", e.getMessage());
                    response.getWriter().println("<h1> Error : " + e.getMessage() + "</h1>");
                    response.getWriter().close();
                }
            }
             
            // Modification du proejt
            if ( action.equals("modifierprojet")){
                try {
                    String id = request.getParameter("pid");
                    Projet project = projectF.find(Integer.parseInt(id));
                    String title = request.getParameter("titre");
                    String description = request.getParameter("description");
                    String dateDebut = request.getParameter("ddebut");
                    String dateFin = request.getParameter("dfin");

                    // Updating the project
                    if ( title != null) project.setTitre(title);
                    if ( description != null) project.setDescription(description);
                    if ( dateDebut != null) project.setDateDebut(dateDebut);
                    if ( dateFin != null) project.setDateFin(dateFin);

                    projectF.edit(project);
                    doGet(request, response);
                    
                }catch (Exception e){
                    request.setAttribute("code", "error");
                    request.setAttribute("message", e.getMessage());
                    response.getWriter().println("<h1> Error : " + e.getMessage() + "</h1>");
                    response.getWriter().close();
                }
            }
        }
        
        
        /**
         * Managing the etapes of the projet
         */
        if ( userPath.equals("/etapes")) {
            String action = request.getParameter("action");
            // Add a step
            if ( action.equals("creer-etape")) {
                String _projet = "";
                try {
                    //String titre = request.getParameter("projet");
                    String etape = request.getParameter("libelle");
                    String dateDebut = request.getParameter("datum1");
                    String dateFin = request.getParameter("datum2");
                    String description = request.getParameter("description");

                    // Get the project
                    _projet = getServletContext().getAttribute("projet").toString();

                    Projet projet = projectF.find(Integer.parseInt(_projet));

                    Etape _etape = pProjects.addStepToProject(projet, etape, description, dateDebut, dateFin);

                    projet.getEtapeList().add(_etape);
                    projectF.edit(projet);
                    getServletContext().setAttribute("etapes", projet.getEtapeList());

                    request.setAttribute("code", "success");
                    request.setAttribute("message", "Nouvelle étape ajouté avec succès !");
                    
                    //url = url + userPath + ".jsp";
                    doGet(request, response);
                    
                }catch (Exception e){
                    request.setAttribute("code", "erreur");
                    request.setAttribute("message", "Une erreur est survenue lors de l'ajout !");
                    System.err.println(" Error cach :: " + e.getMessage());
                    response.getWriter().println("<h1> Error : " + e.getMessage() + "</h1>");
                    response.getWriter().close();
                }
            }
            
            // Modifier une étape
            if (action.equals("modifieretape")){
                try {
                    // Get the step to edit
                    String eid = request.getParameter("eid");
                    Etape _etape = etapeF.find(Integer.parseInt(eid));
                    
                    String etape = request.getParameter("libelle");
                    String dateDebut = request.getParameter("ddebut");
                    String dateFin = request.getParameter("dfin");
                    String description = request.getParameter("description");

                    if ( etape != null && !etape.equals("")) _etape.setLibelle(etape); 
                    if ( dateDebut != null && !dateDebut.equals("")) _etape.setDateDebut(dateDebut);
                    if ( dateFin != null && !dateFin.equals("")) _etape.setDateFin(dateFin);
                    if ( description != null && !description.equals("")) _etape.setDescription(description);

                    etapeF.edit(_etape);

                    request.setAttribute("code", "success");
                    request.setAttribute("message", "Mise à jour effectuée avec succes !");
                    doGet(request, response);
                }catch (Exception e){
                    request.setAttribute("code", "error");
                    request.setAttribute("message", e.getMessage());
                    response.getWriter().println("<h1> Error : " + e.getMessage() + "</h1>");
                    response.getWriter().close();
                }
            }
            
            // Suppression etapes
            if ( action.equals("supprimeretape")){
                try{
                    String projet = request.getQueryString();
                    Projet _projet = projectF.find(Integer.parseInt(projet));

                    String eid = request.getParameter("eid");
                    System.out.println(" OLOLLOLL == " + eid);
                    Etape _etape = etapeF.find(Integer.parseInt(eid));

                    _projet.getEtapeList().remove(_etape);
                    etapeF.remove(_etape);
                    projectF.edit(_projet);
                    //projectF
                    doGet(request, response);
                }catch (Exception ex){
                    response.getWriter().println("<h1> Error : " + ex.getMessage() + "</h1>");
                    response.getWriter().close();
                }
            }
            // when reunion creation
            if ( action.equals("creer-reunion")) {
                // Get the project
                String _projet = getServletContext().getAttribute("projet").toString();

                Projet projet = projectF.find(Integer.parseInt(_projet));
 
                String titre = request.getParameter("titre");
                String description = request.getParameter("description");
                String date = request.getParameter("date");
                String heured = request.getParameter("heure_debut");
                String heuref = request.getParameter("heure_fin");
                String [] participants = request.getParameterValues("participants");
                String salle = request.getParameter("salle_reunion");
                
                try {
                    List<Collaborateur> _participants = new ArrayList<Collaborateur>();
                    for ( String part : participants) {
                        _participants.add(collaboratorF.find(Integer.parseInt(part)));
                    }
                    
                    pCommunication.createMeeting(projet, _participants, titre, description, date, heuref, heuref, salle);

                    doGet(request, response);
                }catch (Exception e){
                    System.err.println(" Error cach :: " + e.getMessage());
                    response.getWriter().println("<h1> Error : " + e.getMessage() + "</h1>");
                    response.getWriter().close();
                }
            }
        }
            
        /**
            * Managing the tasks
            */
        if ( userPath.equals("/taches")){
            String action = request.getParameter("action");
            if ( action.equals("creer-tache")) {
                try {
                    String collaborateur = request.getParameter("collaborateur");
                    String libelle = request.getParameter("libelle");
                    String ddebut = request.getParameter("datum1");
                    String dfin = request.getParameter("datum2");
                    String description = request.getParameter("description");
 
                    // Getting the stape
                    Etape etape = (Etape) getServletContext().getAttribute("etape");
                    Collaborateur _collaborateur = pCollaborateur.getCollaboratorByLogin(collaborateur);
                    Tache task = pProjects.addTaskToStep(etape, libelle, description, ddebut, dfin);

                    etape.getTacheList().add(task);
                    etapeF.edit(etape);
                    pProjects.assignTaskToCollaborator(_collaborateur, task);

                    request.setAttribute("code", "success");
                    request.setAttribute("message", collaborateur + " a été affecté à la tâche créée!");
                    doGet(request, response);

                }catch (Exception e){
                    request.setAttribute("code", "error");
                    request.setAttribute("message", e.getMessage());
                    System.err.println(" Error cach :: " + e.getMessage());
                    response.getWriter().println("<h1> Error : " + e.getMessage() + "</h1>");
                    response.getWriter().close();
                }
            }
            
            if (action.equals("modifiertache")) {
                try {
                    String _tache = request.getParameter("tid");
                    Tache tache = tacheF.find(Integer.parseInt(_tache));

                    String libelle = request.getParameter("libelle");
                    String ddebut = request.getParameter("ddebut");
                    String dfin = request.getParameter("dfin");
                    String description = request.getParameter("description");

                    if ( libelle != null && !libelle.equals("")) tache.setLibelle(libelle);

                    if ( ddebut != null && !ddebut.equals("")) {
                        tache.setDateDebut(ddebut);
                        tache.setDuree(TeamReinforceTimeUtils.calculateDuration(ddebut, tache.getDateFin()));
                    }
                    if ( dfin != null && !dfin.equals("")) {
                        tache.setDateFin(dfin);
                        tache.setDuree(TeamReinforceTimeUtils.calculateDuration(tache.getDateDebut(), dfin));
                        //tache.getEtape().setDuree(tache.getEtape().getDuree() + tache.getDuree());
                    }
                    if ( description != null && !description.equals("")) tache.setDescription(description);

                    tacheF.edit(tache);
                    doGet(request, response);
                }catch (Exception e){
                    request.setAttribute("code", "error");
                    request.setAttribute("message", e.getMessage());
                    response.getWriter().println("<h1> Error : " + e.getCause() + "</h1>");
                    response.getWriter().close();                
                }
            }
           
                        // Suppression etapes
            if ( action.equals("supprimertache")){
                try{
                    String etape = request.getQueryString();
                    Etape _etape = etapeF.find(Integer.parseInt(etape));

                    String tid = request.getParameter("tid");
                    System.out.println(" OLOLLOLL == " + tid);
                    Tache _tache = tacheF.find(Integer.parseInt(tid));
                    _etape.getTacheList().remove(_tache);
                    tacheF.remove(_tache);
                    etapeF.edit(_etape);
                    doGet(request, response);
                }catch (Exception ex){
                    response.getWriter().println("<h1> Error : " + ex.getMessage() + "</h1>");
                    response.getWriter().close();
                }
            }
        }
        
        /**
         * Gestiondesprojets
         */
        if ( userPath.equals("/gestiondesprojets")){
            String action = request.getParameter("action");
            
            // Création du projet
            if ( action.equals("ceerprojet")){
                String title = request.getParameter("titre");
                String description = request.getParameter("description");
                String dateDebut = request.getParameter("ddebut");
                String dateFin = request.getParameter("dfin");
                System.out.println("Title : " + title);
                System.out.println("Description : " + description);
                try {
                    pProjects.createProject(title, description, dateDebut, dateFin);
                    request.setAttribute("code", "success");
                    request.setAttribute("message", "Projet crée avec succès !");
                    doGet(request, response);
                }catch (Exception e){
                    request.setAttribute("code", "error");
                    request.setAttribute("message", e.getMessage());
                    response.getWriter().println("<h1> Error : " + e.getMessage() + "</h1>");
                    response.getWriter().close();
                }
            }
        }
        
        /**
         * Gestion des reunions
         */
        
        if(userPath.equals("/gererlesreunions")){
            String action = request.getParameter("action");
            if ( action.equals("modifierreunion")){
                
                try {
                    String reunion = request.getParameter("rid");
                    Reunion r = reunionF.find(Integer.parseInt(reunion));

                    String titre = request.getParameter("titre");
                    String description = request.getParameter("description");
                    String date = request.getParameter("dater");
                    String hdebut = request.getParameter("hdebut");
                    String hfin = request.getParameter("hfin");
                    String salle = request.getParameter("salle");
                    String [] participants = request.getParameterValues("participants");

                    r.setTitre(titre);
                    r.setDescription(description);
                    r.setDateReunion(date);
                    r.setHeureDebut(hdebut);
                    r.setHeureFin(hfin);
                    r.setSalleReunion(salle);
                    
                    List<Collaborateur> _participants = new ArrayList<Collaborateur>();

                    for ( String part : participants) {
                        if (part != null )
                            _participants.add(collaboratorF.find(Integer.parseInt(part)));
                    }
                    r.setCollaborateurList(_participants);
                    reunionF.edit(r);
                    doGet(request, response);
                }catch (Exception e){
                    e.printStackTrace();
                    response.getWriter().println("<h1> Error : " + e.getMessage() + "</h1>");
                    response.getWriter().close();
                }
            }
        }
    }
 
    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
